import axios from 'axios'
import {ElMessage} from 'element-plus' // 如需弹窗提示可解开
import {logout} from "@/api/userApi.js"

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL + '/user',
    timeout: 30000,  // 请求超时时间
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 可在此处添加token等通用header
        const token = localStorage.getItem('token')
        if (token) config.headers['Authorization'] = `Bearer ${token}`
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 200) {
            return res.data
        } else if (res.code === 401) {
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            ElMessage.error('登录已过期，请重新登录')
            logout().then(() => {
                location.href = '/login'
            })
        } else {
            ElMessage.error(res.msg || '请求失败') // 如需弹窗提示
            return Promise.reject(res.msg || '请求失败')
        }
    },
    error => {
        ElMessage.error(error.message || '网络错误')
        return Promise.reject(error)
    }
)

export default service
